import React, { Component } from 'react';
import { Keyboard, View } from 'react-native';

import {
  Container,
  Content,
  Button,
  Item,
  Input,
  Form,
  Text,
} from 'native-base';
import { Storage } from '../utils';
import theme from '../native-base-theme/variables';
import ZlstIcon from '../components/zlst-icons';
import * as userSecurityInfoService from '../services/userSecurityInfo';
import { UtilToast } from '../utils/util-method';

const INVALID_REG = /[\d\w_]{6,16}/;

class PasswordReset extends Component {
  static navigationOptions = {
    title: '修改密码',
    headerStyle: { backgroundColor: theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  constructor(props) {
    super(props);
    this.state = {
      oldPassword: '',
      newPassword: '',
    };
  }

  get invalid() {
    return this.invalidOldPassword || this.invalidNewPassword;
  }

  get invalidOldPassword() {
    return !(INVALID_REG.test(this.state.oldPassword));
  }

  get invalidNewPassword() {
    return !(INVALID_REG.test(this.state.newPassword));
  }

  _onSubmit = async () => {
    Keyboard.dismiss();

    const resultMsg = await userSecurityInfoService.modifyPassword({
      oldPassword: this.state.oldPassword,
      newPassword: this.state.newPassword,
      userId: global.user.userId,
    });

    UtilToast(resultMsg, 'success');
    this.logout();
  }

  logout = async () => {
    await Storage.set('token.access', null);
    this.props.navigation.navigate({ routeName: 'Login' });
  }

  render() {
    return (
      <Container>
        <Content>
          <Form>
            <Item>
              <Input
                placeholder="旧密码"
                secureTextEntry
                maxLength={16}
                value={this.state.oldPassword}
                onChangeText={(oldPassword) => { this.setState({ oldPassword }); }}
              />
            </Item>
            <Item last>
              <Input
                placeholder="新密码"
                secureTextEntry
                maxLength={16}
                value={this.state.newPassword}
                onChangeText={(newPassword) => { this.setState({ newPassword }); }}
              />
            </Item>
          </Form>
          <Button
            disabled={this.invalid}
            block
            style={{ margin: 15, marginTop: 50 }}
            onPress={this._onSubmit}
          >
            <Text>确认</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default PasswordReset;
